﻿using System;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using Web.Config;
using Web.Constant.Parameter;

namespace AssetManage
{
    public class Global : HttpApplication
    {
        private void Application_Start(object sender, EventArgs e)
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            var rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/");
            if (rootWebConfig.ConnectionStrings.ConnectionStrings["Account_ConnectionString"].ConnectionString !=
                Database.AccountConnectionString)
            {
                rootWebConfig.ConnectionStrings.ConnectionStrings["Account_ConnectionString"].ConnectionString =
                    Database.AccountConnectionString;
            }
            if (rootWebConfig.ConnectionStrings.ConnectionStrings["Expense_ConnectionString"].ConnectionString !=
                Database.AccountConnectionString)
            {
                rootWebConfig.ConnectionStrings.ConnectionStrings["Expense_ConnectionString"].ConnectionString =
                    Database.ExpenseConnectionString;
            }
            Information.RootWebConfig = Server.MapPath("~/Web.config");
            if (Get.SSL() != Information.IsNeedSSL)
            {
                Set.SSL(Information.IsNeedSSL);
            }
            if (Get.CheckDomain(Information.Domain))
            {
                Set.Domain(Information.Domain);
            }
        }

        private void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            var currentContext = ((HttpApplication) sender).Context;
            if (currentContext.User == null) return;
            if (!currentContext.Request.IsAuthenticated) return;
            var identity = (FormsIdentity) currentContext.User.Identity;
            var role = identity.Ticket.UserData.Split(',');
            currentContext.User = new GenericPrincipal(identity, role);
        }
    }
}